# -*- coding: utf-8 -*-
__author__ = 'gongqf'
# import win32com
from win32com.client import Dispatch, constants, DispatchEx
from win32com.client.gencache import EnsureDispatch
import shutil
import qrcode


def gen_qr_pic(id,txt=''):

    qr = qrcode.QRCode(version=None, error_correction=qrcode.constants.ERROR_CORRECT_H,box_size=12,border=1)
    qr.add_data(txt)
    qr.make(fit=True) # Generate the QRCode itself

    # im contains a PIL.Image.Image object
    im = qr.make_image()

    # To save it
    qr_file="E:\\web\\flask\\gis\\qr_%s.png"%id
    im.save(qr_file)
    return qr_file


def gen_card_word(qr_file,card_fibercode='',card_fibername='',card_fibercore='',card_date=''):
    EnsureDispatch('Word.Application') #makepy 导入Word类库，否则constants无法使用
    # w = win32com.client.Dispatch('Word.Application')
    # 或者使用下面的方法，使用启动独立的进程：
    # w = win32com.client.DispatchEx('Word.Application')
    w = DispatchEx('Word.Application')

    # 后台运行，不显示，不警告
    w.Visible = True
    w.DisplayAlerts = True


    word_template=u'E:\\web\\flask\\gis\\光缆模板 - 副本.docx'
    word_work=u'E:\\web\\flask\\gis\\temp.docx'
    shutil.copy(word_template, word_work)

    # 打开新的文件
    doc = w.Documents.Open( FileName = word_work )
    # doc = w.Documents.Add() # 创建新的文档


    # card_fibercode='JD.JYYF/CHL-NCLGJ/HGC/J.48/01'
    # card_fibername=u'世纪东方至交警.世纪东方25楼楼顶监控箱'
    # card_fibercore='GYTS-%sB1'%6
    # card_date='2014-1'

    # wordSel = myRange.Select()
    # expression .Execute(FindText, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward, Wrap, Format, ReplaceWith, Replace, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl)
    # http://msdn.microsoft.com/en-us/library/office/ff193977.aspx
    w.Selection.Find.Execute('card_fibercode', False, False, False, False, False, True, 1, True, card_fibercode, 2)
    w.Selection.Find.Execute('card_fibername', False, False, False, False, False, True, 1, True, card_fibername, 2)
    w.Selection.Find.Execute('card_fibercore', False, False, False, False, False, True, 1, True, card_fibercore, 2)
    w.Selection.Find.Execute('card_date', False, False, False, False, False, True, 1, True, card_date, 2)

    # dc=w.ActiveDocument.Content #取得当前活动文档的内容句柄


    # ishps=w.ActiveDocument.InlineShapes #得到文中所有图片
    shps=w.ActiveDocument.Shapes
    # print shps.Count
    for shp in shps:
        print shp.Left,shp.Top,shp.Height,shp.Width,shp.Line.Visible,shp.Name
    #     shp.Delete()
    #     # shp.Select()
    # shps.AddPicture(u'E:\\web\\flask\\gis\\liantu.png') # AddPicture(FileName As String, [LinkToFile], [SaveWithDocument], [Left], [Top], [Width], [Height], [Anchor])
    # shps[0].Left=203
    shps.AddPicture(qr_file)
    shps[0].Left=155
    shps[0].Top=50
    shps[0].Height=75
    shps[0].Width=75
    # print w.Selection.InlineShapes.Count
    # print w.Selection.InlineShapes[0].Name

    # print ishps.Count,w.Selection.InlineShapes[0].Height
    #w.ActiveDocument.InlineShapes[0].Delete()
    # w.ActiveDocument.Shapes[0].Select()
    # w.ActiveDocument.Shapes.AddPicture(u'E:\\web\\flask\\gis\\liantu.png')  #按序号替换图片

    #
    #
    # doc.PageSetup.PaperSize = 7     # 纸张大小, A3=6, A4=7
    # doc.PageSetup.PageWidth = 8.6*28.35    # 直接设置纸张大小, 使用该设置后PaperSize设置取消
    # doc.PageSetup.PageHeight = 5.49*28.35        # 直接设置纸张大小
    # doc.PageSetup.Orientation = 1                # 页面方向, 竖直=0, 水平=1
    # doc.PageSetup.TopMargin = 1*28.35           # 页边距上=3cm，1cm=28.35pt
    # doc.PageSetup.BottomMargin = 0.3*28.35         # 页边距下=3cm
    # doc.PageSetup.LeftMargin = 0.3*28.35         # 页边距左=2.5cm
    # doc.PageSetup.RightMargin = 0.3*28.35        # 页边距右=2.5cm
    # doc.PageSetup.TextColumns.SetCount(1)        # 设置页面
    #
    # sel = w.Selection       # 获取Selection对象
    # sel.InsertBreak(8)                # 插入分栏符=8, 分页符=7
    # sel.Font.Name = "黑体"                 # 字体
    # sel.Font.Size = 24                     # 字大
    # sel.Font.Bold = True                  # 粗体
    # sel.Font.Italic = True                 # 斜体
    # sel.Font.Underline = True              # 下划线
    # sel.ParagraphFormat.LineSpacing = 2*12   # 设置行距，1行=12磅
    # sel.ParagraphFormat.Alignment = 1      # 段落对齐,0=左对齐,1=居中,2=右对齐
    # sel.TypeText("XXXX")       # 插入文字
    # sel.TypeParagraph()       # 插入空行
    # # 注注注注：：：：ParagraphFormat属性必须使用TypeParagraph()之后才能二次生效！
    #
    # pic = sel.InlineShapes.AddPicture(r'c:\liantu.png') # 插入图片，缺省嵌入型
    # # pic.WrapFormat.Type = 0           # 修改文字环绕方式：0=四周型,1=紧密型,3=文字上方,5=文字下方
    # pic.Borders.OutsideLineStyle = constants.wdLineStyleSingleWavy           # 设置图片4边线,1=实线
    # pic.Borders.OutsideLineWidth = constants.wdLineWidth075pt           # 设置边线宽度，对应对话框中数值依次2,4,6,8,12,18,24,36,48
    # pic.Borders(-1).LineStyle = 1             # -1=上边线,-2=左边线,-3下边线,-4=右边线
    # pic.Borders(-1).LineWidth = 8             # 依次2,4,6,8,12,18,24,36,48
    # # 注注注注：：：：InlineShapes方式插入图片类似于插入字符（嵌入式），Shapes插入图片缺省是浮动的。
    #
    # tab=doc.Tables.Add(sel.Range, 16, 2)  # 增加一个16行2列的表格
    # tab.Style = "网格型"       # 显示表格边框
    # tab.Columns(1).SetWidth(5*28.35, 0)   # 调整第1列宽度，1cm=28.35pt
    # tab.Columns(2).SetWidth(9*28.35, 0)   # 调整第2列宽度
    # tab.Rows.Alignment = 1                    # 表格对齐,0=左对齐,1=居中,2=右对齐
    # tab.CellCellCellCell(1,1).Range.Text = "xxx"    # 填充内容，注意Excel中使用wSheet.Cells(i,j)
    # sel.MoveDown(5, 16)       # 向下移动2行,5=以行为单位
    # # 注注注注：：：：插入n行表格之后必须使用MoveDown(5,n)移动到表格之后才能进行其它操作，否则报错！
    #

    #
    # # 插入文字
    # myRange = worddoc.Range(0,0)
    # myRange.InsertBefore('Hello from Python!')
    #
    # # 使用样式
    # wordSel = myRange.Select()
    # # wordSel.Style = constants.wdStyleHeading1
    #
    # # 正文文字替换
    # w.Selection.Find.ClearFormatting()
    # w.Selection.Find.Replacement.ClearFormatting()
    # w.Selection.Find.Execute('ello', False, False, False, False, False, True, 1, True, '111', 2)
    #
    # # 页眉文字替换
    # w.ActiveDocument.Sections[0].Headers[0].Range.Find.ClearFormatting()
    # w.ActiveDocument.Sections[0].Headers[0].Range.Find.Replacement.ClearFormatting()
    # w.ActiveDocument.Sections[0].Headers[0].Range.Find.Execute('222', False, False, False, False, False, True, 1, False, '223', 2)
    #
    # # 表格操作
    # # worddoc.Tables[0].Rows[0].Cells[0].Range.Text ='123123'
    # # worddoc.Tables[0].Rows.Add() # 增加一行
    #
    # # 转换为html
    # wc = win32com.client.constants
    # w.ActiveDocument.WebOptions.RelyOnCSS = 1
    # w.ActiveDocument.WebOptions.OptimizeForBrowser = 1
    # w.ActiveDocument.WebOptions.BrowserLevel = 0 # constants.wdBrowserLevelV4
    # w.ActiveDocument.WebOptions.OrganizeInFolder = 0
    # w.ActiveDocument.WebOptions.UseLongFileNames = 1
    # w.ActiveDocument.WebOptions.RelyOnVML = 0
    # w.ActiveDocument.WebOptions.AllowPNG = 1
    # # w.ActiveDocument.SaveAs( FileName = 'c:\\1.html', FileFormat = wc.wdFormatHTML )
    #
    # # 打印
    # # worddoc.PrintOut()
    word_file=r'E:\\web\\flask\\gis\\1.docx'
    doc.SaveAs(word_file)
    doc.Close()
    # 关闭
    # doc.Close()
    # w.Documents.Close(wc.wdDoNotSaveChanges)
    w.Quit()
    return word_file

qr_pic_file=gen_qr_pic(12,u'JD.JYYF/CHL-NCLGJ/HGC/J.48/01')
print gen_card_word(qr_pic_file,'2551')